// JobAlumnuInfo.js
import React, { Fragment } from 'react'
import PropTypes from 'prop-types'
import { View, Text, StyleSheet } from 'react-native'
import { MapView } from 'react-native-amap3d'
import { ScaleS, ScaleT } from 'src/utils/ScreenUtil'
import CustomImage from '../../../../components/image/CustomImage'
import CustomButton from '../../../../components/button/CustomButton'
import { IS_IOS, WIDTH } from '../../../../utils/ScreenUtil'
import { getDistance } from '../../../../utils/ConfigUtil'
import { getCurrentPosition } from '../../../../store/actions/landmark'
import { isInstallMap, openAppleMap } from '../../../../utils/NavigateMapUtil'
import { showSelectModal } from '../../../../utils/ModalUtil'
import { CommonToast } from '../../../../utils/ToastUtil'

export default class JobPosition extends React.Component {
  static propTypes = {
    data: PropTypes.array,
    positionActive: PropTypes.number,
    currentLocation: PropTypes.object,
    positionIndexClick: PropTypes.func,
    positionCurrentClick: PropTypes.func
  }

  static defaultProps = {
    data: []
  }

  constructor(props) {
    super(props)
    const data = props.data[props.positionActive] || {}
    this.state = {
      currentLatitude: props.currentLocation.lat,
      currentLongitude: props.currentLocation.lng,
      latitude: Number(data.latitude || 0),
      longitude: Number(data.longitude || 0),
      showCurrentIcon: false,
      positionActive: props.positionActive
    }
  }

  componentDidMount() {
    const data = this.props.data[this.props.positionActive] || {}
    setTimeout(() => {
      this.setState({
        latitude: Number(data.latitude || 0),
        longitude: Number(data.longitude || 0)
      })
    }, 200)
  }

  render() {
    const { data } = this.props
    const { currentLatitude, currentLongitude, showCurrentIcon, latitude, longitude, positionActive } = this.state
    return (
      <View style={styles.container}>
        <View style={styles.titleCont}>
          <Text style={styles.title}>工作地点</Text>
          {/* <Text style={styles.num}>{data.length}</Text> */}
        </View>
        <View style={styles.outMapView}>
          <MapView
            ref={this._mapRef}
            style={styles.mapView}
            coordinate={{ latitude, longitude }}
            zoomLevel={14}
            zoomEnabled={true}
            scrollEnabled={IS_IOS}
            showsZoomControls={false}
            showsCompass={false}
          >
            <MapView.Marker coordinate={{ latitude, longitude }} icon={this._mapIcon}>
            </MapView.Marker>
            {
              showCurrentIcon &&
              <MapView.Marker
                coordinate={{ latitude: Number(currentLatitude || 0), longitude: Number(currentLongitude || 0) }}
                icon={this._currentIcon} />
            }
          </MapView>
          {/* <CustomImage
            style={styles.mapShadow} source={require('src/imgC/home/map_shadow.png')}
            pointerEvents={'none'} /> */}
          <CustomButton style={[styles.mapbtn, styles.mapbtn1]} onPress={this._navigateMap}>
            <CustomImage source={require('src/imgC/post/post_map_navi.png')} />
          </CustomButton>
          <CustomButton style={[styles.mapbtn, styles.mapbtn2]} onPress={this.positionCurrentClick}>
            <CustomImage source={require('src/imgC/post/mapPosition.png')} />
          </CustomButton>
        </View>
        <View styles={styles.listBg}>
          <View style={styles.listWrap}>
            {data.map((item, index) => (
              <Position
                key={index}
                item={item}
                longitude={Number(currentLongitude || 0)}
                latitude={Number(currentLatitude || 0)}
                index={index}
                positionActive={positionActive}
                positionCellClick={this.positionCellClick}
              />
            ))}
          </View>
        </View>
      </View>
    )
  }

  onStartShouldSetResponder = () => {
    console.info('onStartShouldSetResponder')
    return true
  }

  onMoveShouldSetResponder = () => {
    console.info('onMoveShouldSetResponder')
    return true
  }

  _mapRef = (ref) => {
    this._mapView = ref
  }

  _mapIcon = () => {
    return (
      <CustomImage style={styles.mapIcon} source={require('src/imgC/post/mapView_post.png')} />
    )
  }

  _currentIcon = () => {
    return (
      <View style={styles.currentOutView}>
        <View style={styles.currentInnerView} />
      </View>
    )
  }

  /**
   * 打开导航选择
   * @private
   */
  _navigateMap = () => {
    isInstallMap().then((result) => {
      this.selectArr = result.reduce((arr, currentItem) => {
        if (currentItem.supported) {
          arr.push({ label: currentItem.name, navigate: currentItem.navigate })
        }
        return arr
      }, [])
      if (IS_IOS) {
        this.selectArr.push({
          label: '苹果地图', navigate: openAppleMap
        })
      }
      if (this.selectArr.length <= 0) {
        CommonToast('请先下载百度、高德、或腾讯地图')
        return
      }
      this._navigateMapModal = showSelectModal({
        onCancel: this._navigateMapCancel,
        titleText: '选择地图',
        selectArr: this.selectArr,
        selectClick: this._navigateSelectClick
      })
    })
  }

  _navigateSelectClick = (index) => {
    this._navigateMapModal.close(() => {
      const { data, positionActive } = this.props
      const { latitude, longitude, address } = data[positionActive]
      this.selectArr[index].navigate({
        dname: address,
        dlon: longitude,
        dlat: latitude
      })
    })
  }

  _navigateMapCancel = () => {
    this._navigateMapModal.close()
  }

  positionCurrentClick = () => {
    getCurrentPosition().then(({ lat: currentLatitude, lng: currentLongitude }) => {
      this.setState({
        currentLatitude,
        currentLongitude,
        showCurrentIcon: true
      }, () => {
        this._mapAnimateTo(currentLatitude, currentLongitude)
      })
    })
  }

  positionCellClick = index => {
    const { data } = this.props
    const { latitude, longitude } = data[index]
    this._mapAnimateTo(latitude, longitude)
    this.setState({
      latitude,
      longitude,
      positionActive: index
    }, () => {
      this._mapAnimateTo(latitude, longitude)
    })
  }

  _mapAnimateTo = (latitude, longitude) => {
    this._mapView.animateTo({
      zoomLevel: 14,
      coordinate: {
        latitude,
        longitude
      }
    }, 100)
  }
}

const styles = StyleSheet.create({
  container: {
    marginTop: ScaleS(30)
  },
  titleCont: {
    paddingHorizontal: ScaleS(20),
    flexDirection: 'row',
    alignItems: 'flex-start'
  },
  title: {
    marginLeft: ScaleS(2),
    fontSize: ScaleT(16),
    color: '#3c3c3c',
    fontWeight: '500',
    lineHeight: ScaleS(35),
    height: ScaleS(35)
  },
  num: {
    marginLeft: ScaleS(6),
    fontSize: ScaleT(12),
    lineHeight: ScaleS(21),
    height: ScaleS(21),
    marginTop: ScaleS(2)
  },
  des: {
    fontSize: ScaleT(15),
    fontWeight: '400',
    color: '#444444',
    lineHeight: ScaleS(30)
  },
  outMapView: {
    marginTop: ScaleS(20),
    width: WIDTH - ScaleS(40),
    height: ScaleS(130),
    marginHorizontal: ScaleS(20),
    borderRadius: ScaleS(10),
    overflow: 'hidden',
    position: 'relative'
  },
  mapView: {
    position: 'absolute',
    top: 0,
    bottom: 0,
    right: 0,
    left: 0
  },
  mapIcon: {
    width: ScaleS(20),
    height: ScaleS(30),

  },
  mapShadow: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: WIDTH - ScaleS(40),
    height: ScaleS(230),
    resizeMode: 'stretch',
    opacity: 0.5
  },
  mapbtn: {
    position: 'absolute',
    right: ScaleS(10),
    width: ScaleS(38),
    height: ScaleS(38),
    borderRadius: ScaleS(35)
  },
  mapbtn1: {
    top: ScaleS(23)
  },
  mapbtn2: {
    top: ScaleS(75)
  },
  listBg: {
    backgroundColor: '#FFF'
  },
  listWrap: {
    marginBottom: ScaleS(31),
    paddingTop: ScaleS(2),
    paddingRight: ScaleS(19),
    paddingBottom: ScaleS(16),
    paddingLeft: ScaleS(19),
    backgroundColor: '#FFF'
  },
  currentOutView: {
    width: ScaleS(20),
    height: ScaleS(20),
    backgroundColor: '#4287FE',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: ScaleS(10)
  },
  currentInnerView: {
    width: ScaleS(8),
    height: ScaleS(8),
    borderRadius: ScaleS(4),
    backgroundColor: 'white'
  }
})

class Position extends React.Component {
  static propTypes = {
    item: PropTypes.object,
    index: PropTypes.number,
    positionActive: PropTypes.number,
    positionCellClick: PropTypes.func
  }

  click = () => {
    const { positionCellClick, positionActive, index } = this.props
    // if (positionActive !== index) {
    //   positionCellClick(index)
    // }
    positionCellClick(index)
  }

  render() {
    const { item, index, positionActive, longitude, latitude } = this.props
    const active = index === positionActive
    return (
      <CustomButton style={pStyles.container} onPress={this.click}>
        <View style={pStyles.imgPlaceHold}>

          <CustomImage
            style={pStyles.imgCurrent}
            source={active ? require('src/imgC/part/yellow-location.png') : require('src/imgC/post/post_position.png')}
          />
        </View>
        {/* {<Text
          style={[pStyles.distance, active && pStyles.activePosition]}>距离{getDistance(item.latitude, item.longitude, latitude, longitude) || '2560km'} ·</Text>} */}
        <Text style={[pStyles.address, active && pStyles.activePosition]}>{item.latitude && item.longitude && latitude && longitude && ('距离' + getDistance(item.latitude, item.longitude, latitude, longitude) + '·')}{item.address + item.roomInfo}</Text>

      </CustomButton>
    )
  }
}

const pStyles = StyleSheet.create({
  container: {
    marginTop: ScaleS(20),
    flexDirection: 'row',
    alignItems: 'flex-start'
  },
  imgPlaceHold: {
    width: ScaleS(15),
    marginRight: ScaleS(5),
    marginTop: ScaleS(3)
  },
  addressView: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center'
  },
  imgCurrent: {
    height: ScaleS(18)
  },
  address: {
    flex: 1,
    fontSize: ScaleT(15),
    fontWeight: '300',
    textAlign: 'left',
    minHeight: ScaleS(24),
    lineHeight: ScaleS(24),
    color: 'rgba(60, 60, 60, 0.8)'
  },
  distance: {
    textAlign: 'right',
    fontWeight: '300',
    fontSize: ScaleT(15),
    paddingRight: ScaleS(4),
    color: 'rgba(60, 60, 60, 0.8)',
    height: ScaleS(27),
    lineHeight: ScaleS(27)
  },
  activePosition: {
    color: '#3c3c3c'
  }
})
